<?php
namespace app\api\logic;

use app\api\consDir\ErrorConst;
use app\api\services\FriendService;
use app\api\services\MemberService;
use app\api\services\OrderService;
use app\api\services\ShopService;
use app\common\libs\Singleton;
use app\common\models\Community\CommunityOrder;
use app\common\models\Community\CommunityUser;
use app\common\models\Member\Member;
use app\common\utils\CommonUtil;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;

/**
 * 邀请模块
 * Class MemberLogic
 * @package app\api\logic
 */
class FriendLogic extends BaseLogic
{
    use Singleton;

    /**
     * @param $userId
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function friendShopInfo($userId): array
    {
        $shopInfo = ShopService::getInstance()->getShopInfo($userId, 'id,shop_logo,shop_name,create_at,shop_type');

        if (empty($shopInfo)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        //店铺给你收益
        $userShopAmount = FriendService::getInstance()->getUserShopAmount($this->userinfo->id, $userId);

        //店铺订单
        $shopOrderAmountSum = OrderService::getInstance()->getOrderOrderSumByShopId($shopInfo['id']);
        //店铺订单数量
        $shopOrderCount = OrderService::getInstance()->getOrderCountByShopId($shopInfo['id']);

        return ['shopInfo' => $shopInfo, 'userShopAmount' => $userShopAmount, 'shopOrderAmountSum' => $shopOrderAmountSum, 'shopOrderCount' => $shopOrderCount];
    }

    /**
     * @param $page
     * @param $pageSize
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function friendShopList($page, $pageSize): array
    {
        // $this->userinfo->id = 1000151;
        $list = FriendService::getInstance()->friendShopList($this->userinfo->id, $page, $pageSize);
        if (empty($list)) {
            return [];
        }

        $ids  = array_column($list, 'id');
        $fund = FriendService::getInstance()->getUserShopFundSumIds($this->userinfo->id, $ids);
        foreach ($list as &$val) {
            $val['sumMoney'] = $fund[$val['id']] ?? 0;
        }

        $userFinance = MemberService::getInstance()->finance($this->userinfo->id);
        $count       = FriendService::getInstance()->friendShopListCount($this->userinfo->id);
        return [
            'rows'           => $list,
            'userShopCount'  => $count,
            'userShopAmount' => $userFinance['allFriendAmount'],
        ];
    }

    /**
     * @param $userId
     * @param $type
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function friendInfo($userId, $type): array
    {
        $userInfo = MemberService::getInstance()->getUserInfo($userId);
        if (empty($userInfo)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        $info = [
            'avatar'   => $userInfo['avatar'],
            'userName' => $userInfo['userName'],
            'userId'   => $userInfo['userId'],
            'createAt' => $userInfo['createAt'],
        ];
        $userSumAmount        = FriendService::getInstance()->getUserSumAmount($userId, $this->userinfo->id);
        $userFriendCount      = FriendService::getInstance()->getUserFriendCount($userId);
        $userFriendThirdCount = FriendService::getInstance()->getUserFriendThirdCount($userId);

        return ['userInfo' => $info, 'type' => $type, 'userSumAmount' => $userSumAmount, 'userFriendCount' => $userFriendCount, 'userFriendThirdCount' => $userFriendThirdCount];
    }

    /**
     * @param $type
     * @param $page
     * @param $pageSize
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function friendList($type, $page, $pageSize): array
    {
        //type   1一级 2二级 3三级
        switch ($type) {
            case 1:
                $list = FriendService::getInstance()->friendList($this->userinfo->id, $page, $pageSize);
                break;
            case 2:
                $list = FriendService::getInstance()->friendListThird($this->userinfo->id, $page, $pageSize);
                break;
            default:
                $list = FriendService::getInstance()->friendListTeam($this->userinfo->id, $page, $pageSize);
        }

        if (empty($list)) {
            return ['rows' => [], 'allFriendAmount' => 0, 'friendCount' => 0];
        }
        $ids         = array_column($list, 'id');
        $fund        = FriendService::getInstance()->getUserFundSumIds($this->userinfo->id, $ids);
        $userFinance = MemberService::getInstance()->finance($this->userinfo->id);
        //获得直级粉丝总数
        $friendCount = FriendService::getInstance()->getUserFriendCount($this->userinfo->id);

        $ids1    = array_column($list, 'provinceId');
        $ids2    = array_column($list, 'cityId');
        $ids3    = array_column($list, 'countryId');
        $ids4    = array_column($list, 'streetId');
        $ids5    = array_column($list, 'commId');
        $ids     = array_merge($ids1, $ids2, $ids3, $ids4, $ids5);
        $areaMap = empty($ids) ? [] : \think\facade\Db::table('area')
            ->whereIn('this_id', $ids)
            ->column('name', 'this_id');
        // var_dump($areaMap);exit;
        foreach ($list as &$val) {
            $val['sumMoney'] = bcadd($fund[$val['id']] ?? 0, 0, 4);
            $val['phone']    = substr_replace(($val['phone'] ?? ''), "****", 3, 4);
            $val['province'] = $areaMap[$val['provinceId']] ?? '';
            $val['city']     = $areaMap[$val['cityId']] ?? '';
            $val['country']  = $areaMap[$val['countryId']] ?? '';
            $val['street']   = $areaMap[$val['streetId']] ?? '';
            $val['comm']     = $areaMap[$val['commId']] ?? '';
        }
        return ['rows' => $list, 'allFriendAmount' => $userFinance['allFriendAmount'], 'friendCount' => $friendCount];
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function activityList($type, $page, $pageSize): array
    {
        $where = [
            ['m.invite_id','=',$this->userinfo->id]
        ];
        if($type == 1){
            $where[] = ['f.create_at','>=',date('Y-m-d')];
        }
        $list = Member::getInstance()
            ->alias('m')
            ->join('member_click_log f', 'm.id=f.user_id')
            ->where($where)
            ->order('m.id desc')
            ->group('m.id')
            ->page($page,$pageSize)
            ->select()
            ->toArray();
        $friendCount = Member::getInstance()
            ->alias('m')
            ->join('member_click_log f', 'm.id=f.user_id')
            ->where($where)
            ->group('m.id')
            ->count();
        if(empty($list)){
            $list = [];
        }
        foreach($list as &$v){
            $map = [
                ['user_id','=',$v['userId']],
                ['status','=',2]
            ];
            if($type == 1){
                $map[] = ['create_at','>=',date('Y-m-d')];
            }
            $v['isJoin'] = CommunityOrder::getInstance()->where($map)->count();
        }
        $ids1    = array_column($list, 'provinceId');
        $ids2    = array_column($list, 'cityId');
        $ids3    = array_column($list, 'countryId');
        $ids4    = array_column($list, 'streetId');
        $ids5    = array_column($list, 'commId');
        $ids     = array_merge($ids1, $ids2, $ids3, $ids4, $ids5);
        $areaMap = empty($ids) ? [] : \think\facade\Db::table('area')
            ->whereIn('this_id', $ids)
            ->column('name', 'this_id');
        $areaMap = empty($ids) ? [] : \think\facade\Db::table('area')
            ->whereIn('this_id', $ids)
            ->column('name', 'this_id');
        foreach ($list as &$val) {
            $val['phone']    = substr_replace(($val['phone'] ?? ''), "****", 3, 4);
            $val['province'] = $areaMap[$val['provinceId']] ?? '';
            $val['city']     = $areaMap[$val['cityId']] ?? '';
            $val['country']  = $areaMap[$val['countryId']] ?? '';
            $val['street']   = $areaMap[$val['streetId']] ?? '';
            $val['comm']     = $areaMap[$val['commId']] ?? '';
        }

        return ['rows' => $list , 'friendCount' => $friendCount];
    }
}
